package com.security.manage.user.controller;

import com.security.manage.user.dto.ComboDto;
import com.security.manage.user.model.Dept;
import com.security.manage.user.model.ResData;
import com.security.manage.user.model.User;
import com.security.manage.user.repository.DeptRepository;
import com.security.manage.user.repository.UserRepository;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Api("部门管理")
public class DeptController {

    @Resource
    private DeptRepository deptRepository;

    @Resource
    private UserRepository userRepository;

    @PostMapping("/dept")
    public ResData addDept(@RequestBody Dept dept){

        Dept save = deptRepository.save(dept);
        Long deptId = save.getId();
        User admin = userRepository.findByAccount("admin");
        String m = admin.getManageDept();
        if (StringUtils.isEmpty(m)){
            m = String.valueOf(deptId);
        }else{
            m = m+","+deptId;
        }
        admin.setManageDept(m);
        userRepository.save(admin);

        return new ResData(1,"成功");
    }

    @DeleteMapping("/dept/{id}")
    public ResData delDept(@PathVariable("id") Long id){

        List<User> users = userRepository.findByDeptId(id);
        if (users!=null&&users.size()>0){
            return new ResData(0,"有用户绑定了此部门，无法删除");
        }


        deptRepository.deleteById(id);

        //有管理此部门的员工的需要删除
        List<User> deptExist = userRepository.findByManageDeptContaining(String.valueOf(id));
        deptExist.forEach(user -> {
            String m = user.getManageDept();
            List<String> list = new ArrayList<>(Arrays.asList(m.split(",")));
            list.remove(String.valueOf(id));
            m = String.join(",", list);
            user.setManageDept(m);
            userRepository.save(user);
        });


        return new ResData(1,"成功");
    }

    @GetMapping("/dept/users")
    public ResData deptUsers(@RequestParam(value = "manageDept")String manageDept,@RequestParam(value = "type",required = false) Integer type){
        if (StringUtils.isEmpty(manageDept)){
            return new ResData(0,"获取失败",null);
        }
        String[] idArray = StringUtils.split(manageDept, ",");
        List<Long> ids = Arrays.stream(idArray)
                .map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        List<User> users = userRepository.findByDeptIdIn(ids);
        if (users==null|| users.size()==0){
            return new ResData(1,"暂无数据",new ArrayList<>());
        }

        List<User> userList = users.stream().filter(user -> user.getUserType() != 0).collect(Collectors.toList());
        List<ComboDto> comboDtos = new ArrayList<>();
        if (type!=null&&type==1){
            long count = userList.stream().filter(user -> user.getUserType() != 1).count();
            return new ResData<>(1, "获取成功",count);
        }

        userList.forEach(c -> comboDtos.add(new ComboDto(c.getId(),c.getUserName())));
        return new ResData<>(1, "获取成功", comboDtos);
    }

    @GetMapping("/dept/{id}")
    public ResData getDept(@PathVariable("id") Long id){
        Optional<Dept> optionalDept = deptRepository.findById(id);
        return optionalDept.map(dept -> new ResData<>(1, "获取成功", dept)).orElseGet(() -> new ResData(0, "获取失败"));
    }

    @GetMapping("dept/combo")
    public ResData deptCombo(){

        Sort sort = Sort.by(Sort.Direction.ASC, "id");
        Iterable<Dept> all = deptRepository.findAll(sort);
        List<ComboDto> comboDtos = new ArrayList<>();
        all.forEach(dept -> comboDtos.add(new ComboDto(dept.getId(),dept.getName())));
        return new ResData<>(1, "获取成功", comboDtos);
    }

    @GetMapping("dept/list")
    public ResData listDept(@RequestParam(value = "page",defaultValue = "0") Integer page,
                           @RequestParam(value = "size",defaultValue = "10") Integer size){

        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        PageRequest of = PageRequest.of(page, size, sort);
        Page<Dept> pages = deptRepository.findAll(of);

        Map<String,Object> map = new HashMap<>();
        map.put("total",pages.getTotalElements());
        List<Dept> collect = pages.get().collect(Collectors.toList());
        map.put("data",collect);

        return new ResData<>(1, "获取成功", map);
    }
}
